package org.example.aiservice.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.example.aiservice.feign.FileServiceClient;
import org.example.aiservice.pojo.ChatHistory;
import org.example.aiservice.mapper.ChatHistoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class AiChatService extends ServiceImpl<ChatHistoryMapper, ChatHistory> {

    @Autowired
    private FileServiceClient fileServiceClient;

    @Value("${ai.api.url}")
    private String aiApiUrl;

    @Value("${ai.api.key}")
    private String aiApiKey;

    public String chatWithDocument(Long fileId, String question) {
        try {
            // 通过Feign客户端获取文件内容
            String fileContent = fileServiceClient.getFileContent(fileId);
            if (fileContent == null || fileContent.trim().isEmpty()) {
                return "文件内容为空，无法回答问题";
            }

            // 构建提示词
            String prompt = buildPrompt(fileContent, question);

            // 调用AI接口
            String answer = callAiApi(prompt);

            // 保存对话记录
            saveChatHistory(fileId, question, answer);

            return answer;
        } catch (Exception e) {
            return "处理失败: " + e.getMessage();
        }
    }
    //AI接口集成
    private String buildPrompt(String fileContent, String question) {
        StringBuilder prompt = new StringBuilder();
        prompt.append("基于以下文档内容回答问题：\n\n");
        prompt.append("文档内容：\n");
        prompt.append(fileContent);
        prompt.append("\n\n问题：");
        prompt.append(question);
        prompt.append("\n\n请基于文档内容给出准确的回答。如果文档中没有相关信息，请明确说明。");
        return prompt.toString();
    }

    private String callAiApi(String prompt) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(aiApiUrl);
            
            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Authorization", "Bearer " + aiApiKey);

            // 构建请求体（这里使用通用的OpenAI格式，您可以根据实际AI接口调整）
            JSONObject requestBody = new JSONObject();
            requestBody.put("model", "gpt-3.5-turbo");
            requestBody.put("max_tokens", 1000);
            requestBody.put("temperature", 0.7);
            
            JSONObject message = new JSONObject();
            message.put("role", "user");
            message.put("content", prompt);
            requestBody.put("messages", new Object[]{message});

            StringEntity entity = new StringEntity(requestBody.toJSONString(), "UTF-8");
            httpPost.setEntity(entity);

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
                
                // 解析响应（根据实际AI接口格式调整）
                JSONObject responseJson = JSON.parseObject(responseBody);
                if (responseJson.containsKey("choices")) {
                    return responseJson.getJSONArray("choices")
                            .getJSONObject(0)
                            .getJSONObject("message")
                            .getString("content");
                } else if (responseJson.containsKey("error")) {
                    return "AI接口错误: " + responseJson.getJSONObject("error").getString("message");
                } else {
                    return "AI接口返回格式异常";
                }
            }
        } catch (Exception e) {
            return "调用AI接口失败: " + e.getMessage();
        }
    }

    private void saveChatHistory(Long fileId, String question, String answer) {
        ChatHistory chatHistory = new ChatHistory();
        chatHistory.setFileId(fileId);
        chatHistory.setQuestion(question);
        chatHistory.setAnswer(answer);
        chatHistory.setCreatedAt(LocalDateTime.now());
        save(chatHistory);
    }
}